﻿package com.thorqq.magictimer.action;

import android.content.Context;
import android.content.Intent;
import android.provider.Settings;

import com.thorqq.magictimer.core.TAction;
import com.thorqq.magictimer.core.TimerAbs;
import com.thorqq.magictimer.util.Util;

/**
 * 进入退出飞行模式
 * 
 */
public class ActionAirplaneMode extends TAction
{
    private static final long serialVersionUID = 1448793937067510481L;
    protected static final int PARAM_NUM = 1;

    private int mOpen = 1;

    public ActionAirplaneMode(int id, int execOrder, String actionType, String param)
    {
        super(id, execOrder, actionType, param);
    }

    @Override
    public boolean run(Context context, TimerAbs timer)
    {        
        boolean bOpen = IsAirModeOn(context);
        
        if((bOpen && mOpen == 0)
                || (!bOpen && mOpen == 1))
        {
            setAirplaneMode(context, mOpen);
        }
        else
        {
            Util.log("Don't need to switch airplane mode. Airplane mode is " + (bOpen?"on":"off"));
        }

        return true;
    }

    public boolean IsAirModeOn(Context context)
    {
        return (Settings.System.getInt(context.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 0) == 1 ? true : false);
    }

    public static void setAirplaneMode(Context context, int enabling)
    {
        Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,enabling);
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", enabling == 1 ? true : false);
        context.sendBroadcast(intent);
    }

    @Override
    public String getName()
    {
        if (mOpen == 1)
        {
            return "进入飞行模式";
        } 
        else
        {
            return "退出飞行模式";
        }
    }

    @Override
    public String getDescription()
    {
        return null;
    }

    public void setParam(int open)
    {
        mOpen = open;

        this.paramToString();
    }

    @Override
    public boolean parseStringParam()
    {
        String[] array = Util.splitParames(mParam);
        if (array.length != PARAM_NUM)
        {
            Util.log("TimeParam setParam error. param = " + mParam);
            return false;
        }

        mOpen = Util.strToInt(array[0]);

        return true;
    }

    @Override
    public String paramToString()
    {
        StringBuffer sff = new StringBuffer();
        sff.append(mOpen);

        return super.mParam = sff.toString();
    }

}
